/* 
 * This file contains clases and functions for xml output generation.
 */

function XmlElement(name,parentNode) {
    this.name = name;
    this.parentNode = parentNode;
    this.childNodes = new Array();
    this.attributes = new Array();
    this.toXmlString = function(inset) {
        var s = "";
        s += inset + "&lt;"+this.name;
        for(var i = 0; i < this.attributes.length; i++) {
            s += this.attributes[i].toXmlString(" ");
        }
        if(this.childNodes.length > 0) {
            s += "&gt;";
            for(var i = 0; i < this.childNodes.length; i++) {
                s += "<br/>" + this.childNodes[i].toXmlString(inset + "&nbsp;&nbsp;&nbsp;");
            }
            s += "<br/>" + inset + "&lt;/"+this.name+"&gt;";
        } else {
            s += " /&gt;";
        }
        return s;
    };
}

function XmlAttribute(name, value) {
    this.name = name;
    this.value = value;
    this.toXmlString = function(inset) {
        return inset + this.name + "=\""+this.value+"\"";
    };
}

function XmlTextNode(text) {
    this.text = text;
    this.toXmlString = function(inset) {
        return inset + this.text;
    };
}

function XmlCommentNode(text) {
    this.text = text;
    this.toXmlString = function(inset) {
        return inset + "&lt;!-- " + this.text + " --&gt;";
    };
}

function XmlWriter () {
    this.rootNode = null;
    this.currentNode = null;
    this.parentNode = null;
}

XmlWriter.prototype.beginDocument = function(){
    this.rootNode = null;
    this.currentNode = null;
    this.parentNode = null;
};
XmlWriter.prototype.beginNode = function(name){
    var newNode = new XmlElement(name,this.currentNode);
    if(this.rootNode === null) {
        this.rootNode = newNode;
    }
    if(this.parentNode !== null) {
        this.parentNode.childNodes.push(newNode);
    }
    this.currentNode = newNode;
};
XmlWriter.prototype.beginNodeChildren = function(){
    this.parentNode = this.currentNode;
};
XmlWriter.prototype.addTextChild = function(text){
    this.currentNode.childNodes.push(new XmlTextNode(text));
};
XmlWriter.prototype.addAttribute = function(name,value){
    this.currentNode.attributes.push(new XmlAttribute(name,value));
};
XmlWriter.prototype.addCommentChild = function(text){
    this.currentNode.childNodes.push(new XmlCommentNode(text));
};
XmlWriter.prototype.endNodeChildren = function(){
    this.parentNode = this.currentNode.parentNode;
};
XmlWriter.prototype.endNode = function(){
    this.currentNode = this.currentNode.parentNode;
};
XmlWriter.prototype.toString = function(){
    if(this.rootNode !== null) {
        return "<br/><code>" + 
                "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;<br />" + 
                this.rootNode.toXmlString("") + 
                "</code>";
    } else {
        return "";
    }
};
